#pragma once

#include <iostream>
#include <string>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <sys/wait.h>
#include <signal.h>

#include "nocopy.hpp"
#include "Common.hpp"
#include "Log.hpp"
#include "Inet_Addr.hpp"

using namespace LogModule;

static const int g_sockfd = -1; // 缺省的监听套接字
static const int g_backlog = 5; // 全连接队列的最大长度

class TcpServer : public nocopy
{
private:
    // 任务处理
    void Service(int sockfd, Inet_Addr &addr)
    {
        char buffer[1024];
        while (true)
        {
            // 接收消息
            ssize_t n = ::read(sockfd, buffer, sizeof(buffer) - 1);
            if (n > 0)
            {
                buffer[n] = 0;
                LOG(DEBUG, "read success\n");
                // 业务处理
                std::string message = "[" + addr.AddrStr() + "]";
                message += buffer;
                std::cout << message << std::endl;
                // 响应给用户
                n = ::write(sockfd, message.c_str(), message.size());
                if (n < 0)
                {
                    LOG(FATAL, "write error\n");
                    break;
                }
                LOG(INFO, "write success\n");
            }
            else if (n == 0)
            {
                LOG(INFO, "read the end of file\n");
                break;
            }
            else
            {
                LOG(INFO, "read error\n");
                break;
            }
        }
        ::close(sockfd);
    }

public:
    TcpServer(uint16_t port)
        : _listen_sockfd(g_sockfd), _port(port), _isrunning(false)
    {
    }
    // 初始化服务器
    void InitServer()
    {
        // 1、创建监听socket
        _listen_sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
        if (_listen_sockfd < 0)
        {
            LOG(FATAL, "sockfd create error\n");
            exit(SOCKET_ERROR);
        }
        LOG(INFO, "socket create success, sockfd is %d\n", _listen_sockfd);

        // 2、bind ip 和 port
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));   // 清空
        local.sin_family = AF_INET;         // 通信类型 IPv4
        local.sin_addr.s_addr = INADDR_ANY; // 服务端绑定任意ip地址
        local.sin_port = htons(_port);      // 将主机序列转为网络序列
        // 绑定 套接字 和 local
        if (::bind(_listen_sockfd, (struct sockaddr *)&local, sizeof(local)) < 0)
        {
            LOG(FATAL, "bind error\n");
            exit(BIND_ERROR);
        }
        LOG(INFO, "bind success\n");

        // 3、监听
        if (::listen(_listen_sockfd, g_backlog) < 0)
        {
            LOG(INFO, "listen success\n");
            exit(LISTEN_ERROR);
        }
        LOG(INFO, "listen success\n");
    }

    // 启动服务器
    void StartServer()
    {
        signal(SIGCHLD, SIG_IGN);
        _isrunning = true;
        // 长服务
        while (true)
        {
            // 3、接收链接
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int sockfd = ::accept(_listen_sockfd, (struct sockaddr *)&peer, &len);
            if (sockfd < 0)
            {
                LOG(WARNING, "accept error\n");
            }
            LOG(INFO, "accept success, sockfd is %d\n", sockfd);
            // 业务处理
            Inet_Addr addr(peer);
            pid_t id = fork(); // 创建子进程
            if (id == 0)
            {
                // child
                ::close(_listen_sockfd);
                if(fork() > 0)
                    exit(0);// 子进程退出，孙子进程执行业务
                Service(sockfd, addr);
                exit(0);
            }
            // // father
            // ::close(sockfd);
            // pid_t n = waitpid(id, nullptr, 0); // 等待子进程
            // if (n < 0)
            // {
            //     LOG(WARNING, "wait failed\n");
            // }
            // LOG(WARNING, "wait %d success\n", n);
        }
        _isrunning = false;
    }

    ~TcpServer()
    {
        if (_listen_sockfd > g_sockfd)
            ::close(_listen_sockfd);
    }

private:
    int _listen_sockfd; // 监听套接字
    uint16_t _port;     // 端口号
    bool _isrunning;    // 服务端的状态
};